package org.jeecg.modules.order.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.modules.business.dto.PostDataDto;
import org.jeecg.modules.business.entity.BusDictItem;
import org.jeecg.modules.business.entity.BusOrderFee;
import org.jeecg.modules.business.enums.FeeType;
import org.jeecg.modules.business.service.IBusDictItemService;
import org.jeecg.modules.business.service.IBusOrderFeeService;
import org.jeecg.modules.order.entity.CesOrderLeaseGoods;
import org.jeecg.modules.order.service.ICesOrderLeaseGoodsService;
import org.jeecg.modules.rooms.entity.CesRooms;
import org.jeecg.modules.rooms.service.CesRoomsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

 /**
 * @Description: ces_order_lease_goods
 * @Author: jeecg-boot
 * @Date:   2023-04-04
 * @Version: V1.0
 */
@Api(tags="ces_order_lease_goods")
@RestController
@RequestMapping("/order/cesOrderLeaseGoods")
@Slf4j
public class CesOrderLeaseGoodsController extends JeecgController<CesOrderLeaseGoods, ICesOrderLeaseGoodsService> {
	@Autowired
	private ICesOrderLeaseGoodsService cesOrderLeaseGoodsService;
	 @Autowired
	 private CesRoomsServiceImpl cesRoomsService;
	 @Resource
	 private IBusDictItemService busDictItemService;
	 @Resource
	 private IBusOrderFeeService busOrderFeeService;
	/**
	 * 分页列表查询
	 *
	 * @param cesOrderLeaseGoods
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "ces_order_lease_goods-分页列表查询")
	@ApiOperation(value="ces_order_lease_goods-分页列表查询", notes="ces_order_lease_goods-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CesOrderLeaseGoods>> queryPageList(CesOrderLeaseGoods cesOrderLeaseGoods,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														   @RequestParam(name="livingOrderId",required = false) String livingOrderId,
														   @RequestParam(name="startTime",required = false) String startTime,
														   @RequestParam(name="endTime",required = false) String endTime,
								   HttpServletRequest req) {
		Map<String, String[]> map=req.getParameterMap();
		Map writeAbleMap = new HashMap();
		writeAbleMap.putAll(map);
//		writeAbleMap.remove("livingOrderId");
		LambdaQueryWrapper<CesOrderLeaseGoods> queryWrapper = QueryGenerator.initQueryWrapper(cesOrderLeaseGoods, writeAbleMap).lambda();

		if (ObjectUtils.isNotEmpty(startTime)) {
			queryWrapper.ge(CesOrderLeaseGoods::getCreateDate, DateUtil.parseDate(startTime));
		}
		if (ObjectUtils.isNotEmpty(endTime)) {
			queryWrapper.le(CesOrderLeaseGoods::getCreateDate, DateUtil.parseDate(endTime));
		}
//		if(ObjectUtils.isNotEmpty(livingOrderId)) {
//			List<String> livingOrderIds = Arrays.asList(livingOrderId.split(","));
//			queryWrapper.and(i -> {
//				livingOrderIds.forEach(t -> {
//					i.or().eq(CesOrderLeaseGoods::getLivingOrderId, t);
//				});
//			});
//		}
		Page<CesOrderLeaseGoods> page = new Page<CesOrderLeaseGoods>(pageNo, pageSize);
		IPage<CesOrderLeaseGoods> pageList = cesOrderLeaseGoodsService.page(page, queryWrapper);
		pageList.getRecords().forEach(item -> {
			CesRooms rooms = cesRoomsService.getById(item.getRoomId());
			if (rooms != null) {
				item.setRoomNo(rooms.getName());
			}
			BusDictItem busDictItem = busDictItemService.getById(item.getGoodsId());
			if (busDictItem != null) {
				item.setGoodName(busDictItem.getItemText());
			}
			if (item.getOrderFeeId() != null){
				BusOrderFee orderFee = busOrderFeeService.getById(item.getOrderFeeId());
				if (orderFee != null && ObjectUtil.equals(orderFee.getPreferentialStatus(),1)){
					List<BusOrderFee> returnOrderFees = busOrderFeeService.list(Wrappers.<BusOrderFee>lambdaQuery()
							.eq(BusOrderFee::getReturnFeeId, orderFee.getId()).eq(BusOrderFee::getPreferentialStatus, 1));
					BigDecimal returnMoney = returnOrderFees.stream().map(BusOrderFee::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
					item.setDeposit(orderFee.getMoney().add(returnMoney));
					item.setPayType(orderFee.getPayType());
				}
			}
		});
		return Result.OK(pageList);
	}

	 /**
	  * 检查物品是否归还
	  * @param livingOrderId 居住单id
      */
	 @ApiOperation(value="检查物品是否归还", notes="检查物品是否归还")
	 @GetMapping(value = "/checkReturnGoods")
	 public Result<Long> checkReturnGoods(@RequestParam(name="livingOrderId") String livingOrderId) {
		 List<String> livingOrderIds = Arrays.asList(livingOrderId.split(","));
		 LambdaQueryWrapper<CesOrderLeaseGoods> queryWrapper = new LambdaQueryWrapper<>();
		 queryWrapper.isNull(CesOrderLeaseGoods::getRevertDate);
		 queryWrapper.and(i -> {
			 livingOrderIds.forEach(t -> {
				 i.or().eq(CesOrderLeaseGoods::getLivingOrderId, t);
			 });
		 });
		 Long count = cesOrderLeaseGoodsService.count(queryWrapper);
		 return Result.OK(count);
	 }

	 /**
	  * 归还
	  */
	 @AutoLog(value = "归还")
	 @ApiOperation(value="归还", notes="归还")
	 @RequestMapping(value = "/revert", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> revert(@RequestBody PostDataDto dto, boolean returnDeposit) {
		 CesOrderLeaseGoods orderLeaseGood = cesOrderLeaseGoodsService.getById(dto.getId());
		 orderLeaseGood.setRevertDate(new Date());
		 boolean isSuccess = cesOrderLeaseGoodsService.updateById(orderLeaseGood);
		 if (isSuccess && returnDeposit && StrUtil.isNotEmpty(orderLeaseGood.getOrderFeeId())){
			 BusOrderFee leaseGoodFee = busOrderFeeService.getById(orderLeaseGood.getOrderFeeId());
			 if (leaseGoodFee != null){
				 leaseGoodFee.setPreferentialStatus(2);
				 BusOrderFee returnFee = BeanUtil.copyProperties(leaseGoodFee, BusOrderFee.class);
				 returnFee.setId(null);
				 returnFee.setRemark("退还物品押金");
				 returnFee.setCreateTime(new Date());
				 returnFee.setReturnItem(true);
				 returnFee.setReturnFeeId(leaseGoodFee.getId());
				 returnFee.setMoney(leaseGoodFee.getMoney().multiply(BigDecimal.valueOf(-1)));
				 ArrayList<BusOrderFee> orderFeeList = new ArrayList<>();
				 orderFeeList.add(leaseGoodFee);
				 orderFeeList.add(returnFee);
				 busOrderFeeService.saveOrUpdateBatch(orderFeeList);
			 }
		 }
		 return Result.OK("编辑成功!");
	 }

	/**
	 *   添加
	 *
	 * @param cesOrderLeaseGoods 借用物品
	 */
	@AutoLog(value = "ces_order_lease_goods-添加")
	@ApiOperation(value="ces_order_lease_goods-添加", notes="ces_order_lease_goods-添加")
	//@RequiresPermissions("order:ces_order_lease_goods:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CesOrderLeaseGoods cesOrderLeaseGoods) {
		if (cesOrderLeaseGoods.getTenantId() == null || cesOrderLeaseGoods.getTenantId().isEmpty()) {
			LoginUser user = TokenUtils.getAuthUser();
			if (user.getRelTenantIds() != null && !user.getRelTenantIds().isEmpty()) {
				cesOrderLeaseGoods.setTenantId(user.getRelTenantIds());
			} else {
				throw new JeecgBootException("当前登录人租户信息错误");
			}
		}
		if (cesOrderLeaseGoods.getDeposit().compareTo(new BigDecimal(0)) > 0){
			String orderFeeId = addOrderFee(cesOrderLeaseGoods);
			if (orderFeeId == null){
				return Result.error("押金收取失败！");
			}
			cesOrderLeaseGoods.setOrderFeeId(orderFeeId);
		}
		cesOrderLeaseGoods.setOrderNo(DateUtils.getCurrentTimestamp() + "");
		cesOrderLeaseGoods.setCreateDate(new Date());
		cesOrderLeaseGoodsService.save(cesOrderLeaseGoods);
		return Result.OK("添加成功！");
	}

	public String addOrderFee(CesOrderLeaseGoods cesOrderLeaseGoods){
		ArrayList<BusOrderFee> orderFees = new ArrayList<>();
		BusOrderFee busOrderFee = new BusOrderFee();
		busOrderFee.setLivingOrderId(cesOrderLeaseGoods.getLivingOrderId());
		busOrderFee.setRoomId(cesOrderLeaseGoods.getRoomId());
		busOrderFee.setMoney(cesOrderLeaseGoods.getDeposit());
		busOrderFee.setFeeType(FeeType.COLLECTION.getKey());
		busOrderFee.setSubjectType(1);
		busOrderFee.setRemark("物品押金");
		busOrderFee.setPayType(cesOrderLeaseGoods.getPayType());
		busOrderFee.setVipCardId(cesOrderLeaseGoods.getVipCardId());
		busOrderFee.setAgreementUnitId(cesOrderLeaseGoods.getAgreementUnitId());
		busOrderFee.setDayTime(new Date());
		orderFees.add(busOrderFee);
		busOrderFeeService.collectionBatch(orderFees, cesOrderLeaseGoods.getHotelId());
		return busOrderFee.getId();
	}

	 /**
	  *   添加
	  */
	 @AutoLog(value = "ces_order_lease_goods-批量添加")
	 @ApiOperation(value="ces_order_lease_goods-批量添加", notes="ces_order_lease_goods-批量添加")
	 //@RequiresPermissions("order:ces_order_lease_goods:add")
	 @Transactional(rollbackFor = Exception.class)
	 @PostMapping(value = "/addBatch")
	 public Result<String> addBatch(@RequestBody List<CesOrderLeaseGoods> cesOrderLeaseGoodlist) {
		 if (CollUtil.isEmpty(cesOrderLeaseGoodlist)) {
			 return Result.error("没有要借的物品");
		 }
		 LoginUser user = TokenUtils.getAuthUser();
		 if (user.getRelTenantIds() == null || user.getRelTenantIds().equals("")) {
			 throw new JeecgBootException("当前登录人租户信息错误");
		 }
		 cesOrderLeaseGoodlist.forEach(e ->{
			 e.setTenantId(user.getRelTenantIds());
			 if (e.getDeposit().compareTo(new BigDecimal(0)) > 0){
				 String orderFeeId = addOrderFee(e);
				 if (orderFeeId == null){
					 throw new JeecgBootException("押金收取失败");
				 }
				 e.setOrderFeeId(orderFeeId);
			 }
			 e.setOrderNo(DateUtils.getCurrentTimestamp() + "");
			 e.setCreateDate(new Date());
		 });
		 cesOrderLeaseGoodsService.saveBatch(cesOrderLeaseGoodlist);
		 return Result.OK("添加成功！");
	 }

	/**
	 *  编辑
	 *
	 */
	@AutoLog(value = "ces_order_lease_goods-编辑")
	@ApiOperation(value="ces_order_lease_goods-编辑", notes="ces_order_lease_goods-编辑")
	//@RequiresPermissions("order:ces_order_lease_goods:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CesOrderLeaseGoods cesOrderLeaseGoods) {
		cesOrderLeaseGoodsService.updateById(cesOrderLeaseGoods);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ces_order_lease_goods-通过id删除")
	@ApiOperation(value="ces_order_lease_goods-通过id删除", notes="ces_order_lease_goods-通过id删除")
	//@RequiresPermissions("order:ces_order_lease_goods:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		cesOrderLeaseGoodsService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "ces_order_lease_goods-批量删除")
	@ApiOperation(value="ces_order_lease_goods-批量删除", notes="ces_order_lease_goods-批量删除")
	//@RequiresPermissions("order:ces_order_lease_goods:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cesOrderLeaseGoodsService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "ces_order_lease_goods-通过id查询")
	@ApiOperation(value="ces_order_lease_goods-通过id查询", notes="ces_order_lease_goods-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CesOrderLeaseGoods> queryById(@RequestParam(name="id",required=true) String id) {
		CesOrderLeaseGoods cesOrderLeaseGoods = cesOrderLeaseGoodsService.getById(id);
		if(cesOrderLeaseGoods==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(cesOrderLeaseGoods);
	}

	 /**
	  * 通过id查询
	  * @param hotelId
      */
	 //@AutoLog(value = "ces_order_lease_goods-通过id查询")
	 @ApiOperation(value="ces_order_lease_goods-通过id查询", notes="ces_order_lease_goods-通过id查询")
	 @GetMapping(value = "/getLeaseRoom")
	 public Result<List<CesRooms>> getLeaseRoom(String hotelId) {
		 List<CesOrderLeaseGoods> leaseGoodList = cesOrderLeaseGoodsService.list(Wrappers.<CesOrderLeaseGoods>lambdaQuery()
				 .eq(CesOrderLeaseGoods::getHotelId, hotelId).isNull(CesOrderLeaseGoods::getRevertDate));
		 Set<String> roomIds = leaseGoodList.stream().map(CesOrderLeaseGoods::getRoomId).collect(Collectors.toSet());
		 if (roomIds.isEmpty()){
			 return Result.OK(new ArrayList<>());
		 }
		 List<CesRooms> cesRooms = cesRoomsService.list(Wrappers.<CesRooms>lambdaQuery().in(CesRooms::getId, roomIds));
		 return Result.OK(cesRooms);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param cesOrderLeaseGoods
    */
    //@RequiresPermissions("order:ces_order_lease_goods:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CesOrderLeaseGoods cesOrderLeaseGoods) {
        return super.exportXls(request, cesOrderLeaseGoods, CesOrderLeaseGoods.class, "ces_order_lease_goods");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("order:ces_order_lease_goods:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CesOrderLeaseGoods.class);
    }

}
